<template>
  <a-row :gutter="[16, 16]">
    <a-spin :spinning="keywordLoading">
      <a-col :span="14">
        <!-- <a-descriptions :column="1">
        <a-descriptions-item label="待转化成果"> {{ model.achievement }} </a-descriptions-item>
        <a-descriptions-item label="关键词提取"> {{ model.keywords }} </a-descriptions-item>
        <a-descriptions-item label="意向转化地域"> {{ model.provinces }} </a-descriptions-item>
      </a-descriptions> -->

        <div>
          <a-row style="margin: 10px 0">
            <a-col :span="18">
              <div class="column-container">
                <span class="title">待转化成果</span> <span class="content">{{ model.achievement }}</span>
              </div>
            </a-col>
            <a-col :span="6" style="text-align: right">
              <a-button type="primary" @click="handleKeyWord" :loading="keywordLoading"> 关键词生成 </a-button>
            </a-col>
          </a-row>
          <a-row style="margin: 10px 0">
            <a-col :span="18">
              <div class="column-container">
                <span class="title">关键词提取</span>
                <span class="content"> <Jtag v-model="model.keywords"></Jtag></span>
              </div>
            </a-col>
            <a-col :span="6" style="text-align: right">
              <a-button type="primary" :disabled="!model.keywords" @click="handleEdit"> 关键词修改 </a-button>
            </a-col>
          </a-row>
          <a-row style="margin: 10px 0">
            <a-col :span="18">
              <div class="column-container">
                <span class="title">意向转化地域</span>
                <span v-if="!provincesEdit" class="content">{{ model.provinces }}</span>
                <span v-if="provincesEdit" class="content">
                  <j-multi-select-tag v-model="model.provinces" :options="dictOptions" placeholder="请选择意向转化地域">
                  </j-multi-select-tag>
                </span>
              </div>
            </a-col>
            <a-col :span="6" style="text-align: right">
              <a-button type="primary" v-if="!provincesEdit" @click="handleEditProvinces"> 地域修改 </a-button>
              <a-button type="primary" v-if="provincesEdit" @click="handleSaveProvinces"> 保存 </a-button>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: right">
          <a-button type="primary" :disabled="!model.keywords" @click="handleSearch"> 检 索 </a-button>
        </div>
        <div>
          <div class="table-header">
            <div class="title">检索结果</div>
          </div>

          <a-table
            ref="patentTalble"
            :pagination="ipagination"
            :columns="columns"
            :scroll="{ x: 800 }"
            :data-source="patentResultBOS"
            @change="handleTableChange"
          >
            <span slot="title" slot-scope="text, record">
              <a @click="handleDetail(record)">{{ record ? record.title : '' }}</a>
            </span>
            <span slot="action" slot-scope="text, record">
              <a @click="handleAdd(record)" v-if="showBtn(record)">添加备选库</a>
            </span>
          </a-table>
        </div>
        <div>
          <div class="table-header">
            <div class="title">备选库</div>
          </div>
          <a-table
            :columns="columns"
            :pagination="iipagination"
            @change="handleTableChangeI"
            :scroll="{ x: 800 }"
            :data-source="sparePatentResultBOS"
          >
            <span slot="action" slot-scope="text, record">
              <a @click="handleDel(record)">删除</a>
            </span>
          </a-table>
        </div>
        <a-divider />
        <div style="text-align: right">
          <a-button type="primary" @click="handleCreatEsb" :loading="creatLoading" :disabled="!model.keywords">
            生成企业
          </a-button>
        </div>
      </a-col>
      <a-col :span="2"> </a-col>

      <a-col :span="8">
        <a-spin :spinning="creatLoading">
          <a-list item-layout="horizontal" :data-source="enterpriseResultBOS">
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-list-item-meta>
                <a slot="title">{{ item.companyName }}</a>
                <div slot="description">
                  <div><j-ellipsis :value="item.companyProfile" :length="50" /></div>
                  <div>
                    <div>专利列表：</div>
                    <div v-for="(item2, index) in item.patentResultBOS" :key="item2.applicationDocNum">
                      {{ index + 1 }}. {{ item2.title }}
                    </div>
                  </div>
                </div>
              </a-list-item-meta>

              <span slot="extra">
                <a-checkbox :checked="item.isUse == '1'" @change="handleChange($event, item)"> </a-checkbox>
              </span>
            </a-list-item>
          </a-list>

          <a-divider />
          <div style="text-align: right">
            <a-button type="primary" @click="handleReportPreviewPdf" :disabled="!model.keywords"> 生成报告 </a-button>
          </div>
        </a-spin>
      </a-col>
    </a-spin>
    <a-drawer placement="right" width="720" :closable="false" :visible="previewVisible" @close="onClose">
      <div class="flex" slot="title">
        <span>报告预览</span>
        <a @click="handleReportPreview">下载报告</a>
      </div>

      <div id="preview-container">
        <htmlDoc :htmlData="htmlData"></htmlDoc>
      </div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose"> 关闭 </a-button>
      </div>
    </a-drawer>
    <keywordModal ref="keywordModalFrom" @ok="handleOk"></keywordModal>
  </a-row>
</template>

<script>
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import Jtag from '@/components/Jtag'
import { Packer } from 'docxtemplater'
import * as PDFLib from 'pdf-lib'
import mammoth from 'mammoth'
import html2pdf from 'html2pdf.js'
import JSZip from 'jszip'
import keywordModal from './keywordModal.vue'

import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import htmlDoc from './html.vue'
export default {
  name: 'Error',
  components: {
    Jtag,
    keywordModal,
    VueOfficeDocx,
    htmlDoc,
  },
  props: {
    achievementId: {
      type: String,

      required: true,
    },
    reportId: [String, Number],
  },
  data() {
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      iipagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },
      dynamicValidateForm: {
        domains: [],
      },
      columns: [
        {
          title: '申请号',
          dataIndex: 'applicationDocNum',
          width: 160,
        },
        {
          title: '专利名称',
          dataIndex: 'title',
          scopedSlots: { customRender: 'title' },
          ellipsis: true,
        },
        {
          title: '相似度',
          dataIndex: 'sim',
          width: 120,
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
          width: 120,
        },
      ],

      patentResultBOS: [
        { public: '1', title: '2222222', sim: '0.96' },
        { public: '2', title: '2222222', sim: '0.96' },
      ],
      sparePatentResultBOS: [],
      enterpriseResultBOS: [],
      data: [
        {
          title: 'Ant Design Title 1',
        },
        {
          title: 'Ant Design Title 2',
        },
        {
          title: 'Ant Design Title 3',
        },
        {
          title: 'Ant Design Title 4',
        },
      ],
      url: {
        achievement: '/report4/details-achievement',
        keywordCreat: '/report4/keyword-creat',
        keyword: '/report4/keyword',
        province: '/report4/dict/province',
        editDetails: '/report4/editDetails',
        searchMatch: '/report4/search-match',
        sparePatent: '/report4/spare-patent',
        moveSparePatent: '/report4/move-spare-patent',
        creatEsb: '/report4/creat-esb',
        moveEsb: '/report4/move-esb',
        addEsb: '/report4/add-esb',
        reportPreview: '/report4/report-preview',
        reportPreviewPdf: '/report4/report-preview-pdf',
      },
      provincesEdit: false,
      creatLoading: false,
      keywordLoading: false,
      model: {},
      docSrc: '',
      docfileUrl: '',
      previewVisible: false,
      previewContent: null,
      showPreview: false,
      htmlData: {},
    }
  },
  mounted() {
    this.getDetail()
  },
  created() {
    this.initDict()
  },
  methods: {
    handleDetail(record) {
      this.$router.push({
        path: '/know/detail',
        query: { id: record.publicationDocNum },
      })
    },
    initDict() {
      getAction(this.url.province).then((res) => {
        if (res.success) {
          this.dictOptions = res.result.map((e) => {
            return {
              label: e.description,
              value: e.description,
            }
          })
          console.log(this.dictOptions)
        }
      })
    },

    handleTableChange(pagination, filters, sorter) {
      console.log('Various parameters', pagination, filters, sorter)
      this.ipagination = pagination
    },
    handleTableChangeI(pagination, filters, sorter) {
      console.log('Various parameters', pagination, filters, sorter)
      this.iipagination = pagination
    },
    getDetail() {
      this.ipagination.current = 1
      this.iipagination.current = 1
      console.log(this.$refs.patentTalble)
      let id = this.achievementId
      var that = this
      this.keywordLoading = true
      getAction(that.url.achievement + '/' + id)
        .then((res) => {
          if (res.success) {
            this.model = res.result
            this.patentResultBOS = res.result.patentResultBOS
            this.sparePatentResultBOS = res.result.sparePatentResultBOS
            this.enterpriseResultBOS = res.result.enterpriseResultBOS
            this.ipagination.total = res.result.patentResultBOS.length
          }
        })
        .finally(() => {
          this.keywordLoading = false
        })
    },
    handleSaveProvinces() {
      let obj = {
        reportId: this.reportId,
        provinces: this.model.provinces,
      }
      postAction(this.url.editDetails, obj).then((res) => {
        if (res.success) {
          this.provincesEdit = false
        }
      })
    },
    handleEditProvinces() {
      this.provincesEdit = true
    },
    handleEdit() {
      let id = this.achievementId
      this.$refs.keywordModalFrom.edit(id)
    },
    handleKeyWord() {
      let id = this.achievementId
      this.keywordLoading = true
      getAction(this.url.keywordCreat + '/' + id)
        .then((res) => {
          if (res.success) {
            this.model.keywords = res.result
          }
        })
        .finally(() => {
          this.keywordLoading = false
        })
    },
    renderedHandler() {
      console.log('渲染完成')
    },
    errorHandler(e) {
      console.log('渲染失败')
      console.log(e)
    },
    handleAdd(record) {
      let obj = {
        ids: [record.reportSparePatentId],
      }
      postAction(this.url.sparePatent, obj).then((res) => {
        if (res.success) {
          this.sparePatentResultBOS.push(record)
        }
      })
    },
    handleSearch() {
      let id = this.achievementId
      getAction(this.url.searchMatch + '/' + id).then((res) => {
        if (res.success) {
          this.getDetail()
        }
      })
    },
    showBtn(record) {
      const index = this.sparePatentResultBOS.findIndex((item) => item.applicationDocNum === record.applicationDocNum)
      if (index !== -1) {
        return false
      } else {
        return true
      }
    },
    handleDel(record) {
      let id = record.reportSparePatentId
      deleteAction(this.url.moveSparePatent + '/' + id).then((res) => {
        if (res.success) {
          const index = this.sparePatentResultBOS.findIndex((item) => item.public === record.public)
          if (index !== -1) {
            this.sparePatentResultBOS.splice(index, 1) // 删除找到的那一项
          }
        }
      })
    },
    handleCreatEsb() {
      let id = this.achievementId
      var that = this
      this.creatLoading = true
      getAction(that.url.creatEsb + '/' + id)
        .then((res) => {
          if (res.success) {
            this.getDetail()
          }
        })
        .finally(() => {
          this.creatLoading = false
        })
    },
    handleChange(e, item) {
      let id = item.reportAchievementId
      let index = this.enterpriseResultBOS.indexOf(item)
      if (index != -1) {
        if (this.enterpriseResultBOS[index].isUse == '1') {
          deleteAction(this.url.moveEsb + '/' + id).then((res) => {
            if (res.success) {
              this.enterpriseResultBOS[index].isUse = 0
            }
          })
        } else {
          getAction(this.url.addEsb + '/' + id).then((res) => {
            if (res.success) {
              this.enterpriseResultBOS[index].isUse = 1
            }
          })
        }
      }

      //如果是邮件类型那么则改变模板内容是富文本编辑器
    },

    handleReportPreviewPdf() {
      let id = this.achievementId
      var that = this
      getAction(that.url.achievement + '/' + id).then((res) => {
        if (res.success) {
          if (res.result.sparePatentResultBOS && res.result.sparePatentResultBOS.length > 0) {
            this.htmlData = res.result

            this.previewVisible = true
          } else {
            this.$message.error('请在备选库添加文件,否则无法生成报告')
          }
        }
      })
    },
    handleReportPreview() {
      let id = this.achievementId
      var that = this

      // 显示加载提示

      downFile(
        that.url.reportPreview + '/' + id,
        {
          responseType: 'arraybuffer',
        },
        'post'
      )
        .then(async (res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          })
          const fileURL = URL.createObjectURL(blob)

          // 用于调试：直接下载为 .docx 文件
          const a = document.createElement('a')
          a.href = fileURL
          a.download = 'document.docx'
          document.body.appendChild(a)
          a.click()
        })
        .catch((error) => {
          this.$message.error('获取文件失败：' + error.message)
          loading.close()
        })
    },

    onClose() {
      this.previewVisible = false
    },
    handleOk() {
      this.getDetail()
    },
  },
  renderedHandler() {},
  errorHandler() {},
  async previewPDF(pdfBlob) {
    const pdfURL = URL.createObjectURL(pdfBlob)
    const iframe = document.createElement('iframe')
    iframe.src = pdfURL
    iframe.width = '100%'
    iframe.height = '600px'
    document.body.appendChild(iframe)
  },
}
</script>

<style lang="less" scoped>
a {
}
.column-container {
  display: table;
  width: 100%;

  span {
    display: table-cell;
    word-wrap: break-word; /* 内容过长时自动换行 */
    white-space: normal;
    padding-right: 10px; /* 可选：设置单元格间距 */
    vertical-align: top; /* 强制文字顶部对齐 */
  }
  .title {
    display: inline-block; /* 或者使用 block */
    width: 25%; /* 设置第一个 span 的宽度为 15% */
    font-weight: 600;
  }
  .title::after {
    content: ':'; /* 添加的伪元素内容，例如中文冒号 */
    font-weight: bold; /* 可选：设置伪元素样式 */
    margin-left: 4px; /* 可选：与标题内容之间的间距 */
  }
  .content {
    display: inline-block; /* 或者使用 block */
    width: 75%; /* 设置第二个 span 的宽度为 85% */
  }
}

.table-header {
  .title {
    font-size: 20px;
    margin: 10px 0;
  }
}
.ant-list-item {
}
.preview-content {
  min-height: 400px;
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
.flex {
  display: flex;
  justify-content: space-between;
}
</style>